import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_app_update/flutter_app_update.dart';
import 'package:flutter_app_update/result_model.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/app_version_entity.dart';
import 'package:package_info_plus/package_info_plus.dart';

class VersionController extends GetxController {
  String? currentVersion;

  static VersionController get to => Get.find();

  @override
  void onInit() {
    super.onInit();

    _initPageInfo();
    AzhonAppUpdate.listener((ResultModel model) {
      debugPrint('$model');
    });
  }

  Future<void> _initPageInfo() async {
    final PackageInfo packageInfo = await PackageInfo.fromPlatform();
    currentVersion = packageInfo.version;
  }

  //判断version大小
  Future<void> requestVersion(bool isShowToast) async {
    final platform = GetPlatform.isAndroid ? '1' : '2';
    AppVersionEntity? entity = await DefaultApi()
        .oraAppVersionQueryPlatformGet<AppVersionEntity>(platform: platform);

    // entity?.data?.version='0.0.10';
    entity?.data?.mustRenew = 0;
    // entity?.data?.downUrl =
    // "https://imtt.dd.qq.com/16891/apk/FA48766BA12A41A1D619CB4B152889C6.apk?fsname=com.estrongs.android.pop_4.2.3.3_10089.apk&csr=1bbd";

    bool isUpdate = false;
    if (entity?.data != null && currentVersion?.isNotEmpty == true) {
      List<int> newVersion =
          entity!.data!.version!.split('.').map(int.parse).toList();

      List<int> version = currentVersion!.split('.').map(int.parse).toList();
      int maxLength = max(newVersion.length, version.length);
      for (var index = 0; index < maxLength; index++) {
        int newVersionPart = index < newVersion.length ? newVersion[index] : 0;
        int versionPart = index < version.length ? version[index] : 0;
        if (newVersionPart != versionPart) {
          isUpdate = newVersionPart > versionPart;
          break;
        }
      }
    }
    if (isUpdate) {
      showUpdateDialog(entity!.data!);
    } else if (isShowToast) {
      Toast.show(TextKey.latestVersion.tr);
    }
  }

  @override
  void onClose() {
    super.onClose();
    AzhonAppUpdate.dispose();
  }

  showUpdateDialog(AppVersionData data) {
    final bool forcedUpgrade = data.mustRenew == 1;
    showDialog(
      context: Get.context!,
      barrierDismissible: !forcedUpgrade,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () => Future.value(!forcedUpgrade),
          child: AlertDialog(
            title: Text(TextKey.newVersionTitle.tr),
            content: Text(data.describe ?? ''),
            actions: <Widget>[
              if (!forcedUpgrade)
                TextButton(
                  child: Text(TextKey.cancel.tr),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              TextButton(
                child: Text(TextKey.update.tr),
                onPressed: () {
                  _appUpdate(data);
                  if (!forcedUpgrade) {
                    Navigator.of(context).pop();
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  _appUpdate(AppVersionData data) {
    if (data.downUrl?.isURL == true) {
      UpdateModel model = UpdateModel(
        data.downUrl!,
        "oramemoUpdate.apk",
        "ic_launcher",
        data.downUrl!,
      );
      AzhonAppUpdate.update(model);
    }else{
      Toast.show(TextKey.downloadLinkError.tr);
    }
  }
}
